package com.sita.cfmoto.my.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.EditText;

import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.model.BindedVehicle;
import com.sita.cfmoto.shouye.CaptureActivityAnyOrientation;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.activity.MainActivity;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.PersistUtils;
import com.sita.cfmoto.utils.VehicleUtils;
import com.sita.cfmoto.utils.ToastTool;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import rx.Subscription;

public class BindVehicleActivity extends AppCompatActivity {
    @Bind(R.id.vehicle_sn_edit)
    EditText mSn;
    @Bind(R.id.vehicle_sn_pwd_edit)
    EditText mPwd;
    private String sn;
    private String snPwd;
    private Subscription subscription;
    private ScanField mScanField;
    private boolean isToMain;

    public static Intent newIntent() {
        return new Intent(GlobalContext.getGlobalContext(), BindVehicleActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_vehicle);
        isToMain = getIntent().getBooleanExtra("isToMain", true);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.scan_sn_img)
    void clickScanVin() {
        mScanField = ScanField.VIN;
//        new IntentIntegrator(this).initiateScan();
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setCaptureActivity(CaptureActivityAnyOrientation.class);
        integrator.setOrientationLocked(false);
        integrator.setPrompt("");
        integrator.initiateScan();
    }

    @OnClick(R.id.scan_sn_pwd_img)
    void clickScanVinPwd() {
        mScanField = ScanField.VIN_PWD;
//        new IntentIntegrator(this).initiateScan();
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setCaptureActivity(CaptureActivityAnyOrientation.class);
        integrator.setOrientationLocked(false);
        integrator.setPrompt("");
        integrator.initiateScan();
    }

    @OnClick(R.id.back_img)
    void onClickBack() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
            } else {
                if (mScanField == ScanField.VIN) {
                    mSn.setText(result.getContents());
                } else if (mScanField == ScanField.VIN_PWD) {
                    mPwd.setText(result.getContents());
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick(R.id.bind_btn)
    void bindVehicle() {
        sn = mSn.getText().toString();
        snPwd = mPwd.getText().toString();
//        snPwd = "123455";
        if (TextUtils.isEmpty(sn) || TextUtils.isEmpty(snPwd)) {
//        if (TextUtils.isEmpty(sn)) {
            final NormalDialog dialog = new NormalDialog(this);
            dialog.style(NormalDialog.STYLE_TWO)
                    .titleLineColor(getResources().getColor(R.color.blue))
                    .titleTextSize(20)
                    .title(getString(R.string.warm_tips))
                    .contentTextColor(getResources().getColor(R.color.black))
                    .contentGravity(Gravity.CENTER)
                    .content(getString(R.string.binding_vehicle_wrong_sn))
                    .show();
            dialog.setOnBtnClickL(
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                        }
                    });
            return;
        }

        VehicleUtils.fetchBindedVehicleWithoutSave(sn, VehicleUtils.DEFAULT_GPS_VENDOR, snPwd, new VehicleUtils.FetchBindedVehicleCallback() {
            @Override
            public void onFetchBindedVehicle(BindedVehicle vehicle) {
                if (vehicle == null) {
                    ToastUtils.show(GlobalContext.getGlobalContext(), "没有找到车辆记录");
                    return;
                }
//                VehicleUtils.vehicleBean.controllerAddr = vehicle.controllerAddress;
//                VehicleUtils.vehicleBean.controllerKey = vehicle.controllerPassword;
                sendBindResultToServer();
            }
        });

    }

    private void sendBindResultToServer() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.activate_vehicle)
                .content(R.string.activating_vehicle)
                .progress(true, 15000)
                .build();
        dialog.show();

        BindedVehicle vehicle = new BindedVehicle();
        vehicle.vin = sn;
        vehicle.password = snPwd;
        vehicle.vincpy = VehicleUtils.DEFAULT_GPS_VENDOR;

        VehicleUtils.bindVehicle(vehicle, new VehicleUtils.BindVehicleCallback() {
            @Override
            public void onBindVehicleSuccess(String vehicleSn) {
                if (vehicleSn != null) {
                    VehicleUtils.fetchBindedVehicle(sn, VehicleUtils.DEFAULT_GPS_VENDOR, snPwd,
                            new VehicleUtils.FetchBindedVehicleCallback() {
                                @Override
                                public void onFetchBindedVehicle(BindedVehicle vehicle) {
                                    if (vehicle != null) {
                                        PersistUtils.saveBindedVehicle(vehicle);
                                        LocalStorage.setCurrSelectedVehicle(vehicle.vin);
                                        dialog.dismiss();
                                        if (isToMain) {
                                            startActivity(new Intent(BindVehicleActivity.this, MainActivity.class));
                                        }
                                        BindVehicleActivity.this.finish();
                                    } else {
                                        dialog.dismiss();
                                    }
                                }
                            });
                } else {
                    dialog.dismiss();
                }
            }

            @Override
            public void onBindVehicleFailed(Throwable cause) {
                ToastTool.showDebugMessage(com.sita.cfmoto.utils.TextUtils.getThrowableMessage(cause));
                dialog.dismiss();
            }
        });
    }

    private void onActivateFailed() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.style(NormalDialog.STYLE_TWO)
                .titleLineColor(getResources().getColor(R.color.blue))
                .titleTextSize(20)
                .title(getString(R.string.warm_tips))
                .contentTextColor(getResources().getColor(R.color.black))
                .contentGravity(Gravity.CENTER)
                .content(getString(R.string.activation_error))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                });

    }

    private enum ScanField {
        VIN, VIN_PWD
    }
}
